package com.xinjian.jianba.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.filter.ContentCachingRequestWrapper;
import com.xinjian.jianba.filter.ParameterFilter;
import com.xinjian.jianba.utils.Constants;


/**
 * 拦截器.
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

	private static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfigurer.class);

	@Value("${excludeUrl}")
	private String excludeUrls;
	@Autowired
	private UserInfoDao userInfoDao;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptorAdapter() {

			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {
				// 过滤不需要拦截的url
				String requestUri = request.getRequestURI();
				LOGGER.info("拦截器 WebMvcConfigurer->requestUri={}", requestUri);
				if (excludeUrls != null && excludeUrls.trim().length() > 0) {
					String[] excludeUrlArr = excludeUrls.split(";");
					for (String excludeUrl : excludeUrlArr) {
						if (requestUri.indexOf(excludeUrl) != -1) {
							return true;
						}
						//活动借口不校验token
						if(requestUri.indexOf("/api/v3/jianba/tickets")!=-1){
							return true;
						}
					}
				}

				// 获取token
				String token = request.getHeader(Constants.TOKEN);
				LOGGER.info("-----拦截器 WebMvcConfigurer------>token={}", token);
				// 身份认证
				if (StringUtils.isBlank(token)) {
					throw new BusinessException(ResponseCode.CODE_401, "请重新登录!");
				} else {
					UserInfoEnity userInfo = new UserInfoEnity();
					userInfo.setPushToken(token);
					List<UserInfoEnity> isRegist = userInfoDao.select(userInfo);
					if (CollectionUtils.isEmpty(isRegist)) {
						throw new BusinessException(ResponseCode.CODE_401, "请重新登录!");
					}
					return true;
				}
			}
		}).addPathPatterns("/**");
	}
	@Bean
    public FilterRegistrationBean parameterFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        ParameterFilter parameterFilter = new ParameterFilter();
        registration.setFilter(parameterFilter);
        registration.addUrlPatterns("/*");
        registration.setOrder(1);
        return registration;
    }
}
